<template>
  <el-drawer v-model="drawerFlag" direction="rtl">
    <template #header>{{ title }}</template>
    <template #default>
      <el-form :model="formModel" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="字符" prop="character">
          <el-input v-model="formModel.character"></el-input>
        </el-form-item>
        <el-form-item label="结构" prop="structure_id">
          <el-select v-model="formModel.structure_id" placeholder="请选择结构" style="width: 100%">
            <el-option v-for="item in structureList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="偏旁" prop="radical_id">
          <el-select v-model="formModel.radical_id" placeholder="请选择结构" style="width: 100%">
            <el-option v-for="item in radicalList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="SVG路径" prop="svg_path">
          <el-image :src="formModel.svg_path" />
          <UploadOss v-model="formModel.svg_path" />
        </el-form-item>
        <el-form-item label="笔画数" prop="stroke_count">
          <el-input-number v-model="formModel.stroke_count" controls-position="right">
            <template #decrease-icon>
              <el-icon>
                <Minus />
              </el-icon>
            </template>
            <template #increase-icon>
              <el-icon>
                <Plus />
              </el-icon>
            </template>
          </el-input-number>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleClickBtnCancel">取消</el-button>
        <el-button type="primary" @click="handleClickBtnSubmit">提交</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import Dal from '@/dal'
import { ElMessage } from 'element-plus'
import { Minus, Plus } from '@element-plus/icons-vue'
import type { ElForm } from 'element-plus'
import UploadOss from '@/components/Common/UploadOss.vue'

const emits = defineEmits(['close', 'submited'])
const drawerFlag = ref(false)
const title = ref('')
const structureList = ref<any[]>([])
const radicalList = ref<any[]>([])

const formRef = ref<InstanceType<typeof ElForm>>()

const formModel = reactive({
  id: null,
  character: '',
  structure_id: '',
  radical_id: '',
  svg_path: '',
  stroke_count: 0,
})

const rules = reactive({
  character: [{ required: true, message: '请输入字符', trigger: 'blur' }],
  structure_id: [{ required: true, message: '请输入结构ID', trigger: 'blur' }],
  radical_id: [{ required: true, message: '请输入偏旁ID', trigger: 'blur' }],
  svg_path: [{ required: true, message: '请输入SVG路径', trigger: 'blur' }],
  stroke_count: [{ required: true, message: '请输入笔画数', trigger: 'blur' }],
})

const handleClickBtnCancel = () => {
  formRef.value?.resetFields()
  drawerFlag.value = false
}

/**
 * 异步处理按钮点击事件
 */
const handleClickBtnSubmit = async () => {
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        let res: any = null
        if (formModel.id) {
          // 编辑
          res = await Dal.Hanzi.Character.update(formModel)
        } else {
          // 新建
          res = await Dal.Hanzi.Character.create(formModel)
        }
        // await Dal.Hanzi.Pinyin.create({
        //   hanzi_id: res.data.id,
        //   pinyin: formModel.pinyin.join(',')
        // })
        ElMessage({ message: '提交成功', type: 'success' })
        emits('submited', { ...formModel })
      } catch (error) {
        console.error('提交失败', error)
        ElMessage({ message: '提交失败', type: 'error' })
      }
    } else {
      console.log('表单验证失败')
    }
  })
  drawerFlag.value = false
}

/**
 * 打开汉字编辑页面
 *
 * @param data 要编辑的汉字数据
 * @param options 选项，包含标题等
 */
const open = async (data: any, options: any = {}) => {
  drawerFlag.value = true

  await setStructureList()
  await setRadicalList()

  title.value = options.title || '编辑汉字字符'
  if (data.id) {
    const res = await Dal.Hanzi.Character.findById(data.id)
    Object.assign(formModel, res)
  } else {
    formModel.id = null
    formModel.character = ''
    formModel.structure_id = ''
    formModel.radical_id = ''
    formModel.svg_path = ''
    formModel.stroke_count = 0
  }
}
/**
 * 异步设置结构列表
 *
 * @returns Promise<void> 无返回值
 */
const setStructureList = async () => {
  const res = await Dal.Hanzi.Structure.findAll()
  structureList.value = res.data.map((item: any) => ({ value: item.id, label: item.name }))
}
/**
 * 异步设置汉字部首列表
 *
 * @returns 无返回值
 */
const setRadicalList = async () => {
  const res = await Dal.Hanzi.Radical.findAll()
  radicalList.value = res.data.map((item: any) => ({ value: item.id, label: `${item.radical}-${item.name}` }))
}

defineExpose({
  open,
})
</script>
<style lang="scss" scoped>
.pinyin-cell {
  display: flex;

  .btn {
    margin-left: 12px;
  }
}
</style>
